package net.lookyou.boot.demo.config.security;

import net.lookyou.boot.demo.entity.SysUser;
import net.lookyou.boot.demo.mapper.UserMapper;
import net.lookyou.boot.demo.utils.PasswordUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 *  <p> 自定义认证处理 </p>
 *
 * @description :
 * @author : zhengqing
 * @date : 2019/10/12 14:49
 */
@Component
public class CustomerAuthenticationProvider implements AuthenticationProvider {

    @Resource
    CustomerUserDetailsService userDetailsService;
    @Resource
    private UserMapper userMapper;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取前端表单中输入后返回的用户名、密码
        String userName = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();

        if(StringUtils.isBlank(userName)){
            throw new UsernameNotFoundException("用户名不能为空");
        }

        if(StringUtils.isBlank(password)){
            throw new BadCredentialsException("密码不能为空");
        }

        User userInfo = (User) userDetailsService.loadUserByUsername(userName);
        if(Objects.isNull(userInfo)){
            throw new UsernameNotFoundException("用户不存在");
        }

        SysUser currentUser = userMapper.selectOne(new SysUser() {{
            setUsername(userName);
        }});

        // 验证密码
        if (!PasswordUtils.isValidPassword(password, userInfo.getPassword(), currentUser.getSalt())) {
            throw new BadCredentialsException("密码错误！");
        }

        // 前后端分离情况下 处理逻辑...
        // 更新登录令牌 - 之后访问系统其它接口直接通过token认证用户权限...
        String token = PasswordUtils.encodePassword(System.currentTimeMillis() + currentUser.getUsername(), currentUser.getSalt());
        currentUser.setToken(token);
        userMapper.updateById(currentUser);

        return new UsernamePasswordAuthenticationToken(userInfo, password, userInfo.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
